package cn.yangliu.nacos.management.config;

import java.util.Collections;

import cn.yangliu.nacos.comm.model.Oauth2Token;
import cn.yangliu.nacos.comm.model.Oauth2UserModel;
import cn.yangliu.nacos.comm.oauth.Oauth2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-01
 */
@Component
public class SecurityAuthenticationProvider implements AuthenticationProvider {

    /**
     * current class instance's member.
     * The Oauth 2 service.
     */
    @Autowired
    private Oauth2Service oauth2Service;

    /**
     * Authenticate authentication.
     *
     * @param authentication the authentication
     * @return the authentication
     * @throws AuthenticationException the authentication exception
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        Oauth2Token oauth2Token = oauth2Service.login(username, password);
        Oauth2UserModel oauth2UserModel = oauth2Service.principal(oauth2Token.getAccessToken());
        return new UsernamePasswordAuthenticationToken(oauth2UserModel, password, Collections.emptyList());
    }

    /**
     * Supports boolean.
     *
     * @param authentication the authentication
     * @return the boolean
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
